package com.pxy.test;

import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;

/**
 * Created by PXY on 2017/9/2.
 */

public class MyTextView extends android.support.v7.widget.AppCompatTextView {

    public MyTextView(Context context) {
        super(context);
    }

    public MyTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        mLongPressRunnable = new Runnable() {
            @Override
            public void run() {
                performLongClick();
//                performClick();
            }
        };
    }

    public MyTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
    private int mLastMotionX, mLastMotionY;
    //是否移动了
    private boolean isMoved;

    private long lastDownTime;
    private long lastUpTime;
    //长按的runnable
    private Runnable mLongPressRunnable;
    //移动的阈值
    private static final int TOUCH_SLOP = 20;

    private LongClickListener mLongClickListener;

    public boolean dispatchTouchEvent(MotionEvent event) {
        int x = (int) event.getX();
        int y = (int) event.getY();

        switch(event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mLastMotionX = x;
                mLastMotionY = y;
                isMoved = false;
                lastDownTime=event.getDownTime();
                Log.e("PXY", "dispatchTouchEvent: "+lastDownTime );
                postDelayed(mLongPressRunnable, 5000);
                setBackgroundResource(R.color.white_pressed);
                break;
            case MotionEvent.ACTION_MOVE:
                if(isMoved) break;
                if(Math.abs(mLastMotionX-x) > TOUCH_SLOP
                        || Math.abs(mLastMotionY-y) > TOUCH_SLOP) {
                    //移动超过阈值，则表示移动了
                    isMoved = true;
                    removeCallbacks(mLongPressRunnable);
                }
                break;
            case MotionEvent.ACTION_UP:
                //释放了
                lastUpTime=event.getEventTime();
                Log.e("PXY", "dispatchTouchEvent: "+lastUpTime );
                Log.e("PXY", "dispatchTouchEvent: "+Math.abs(lastUpTime-lastDownTime) );
                if(Math.abs(lastUpTime-lastDownTime)<5000){
                   performClick();
                }
                removeCallbacks(mLongPressRunnable);
                setBackgroundResource(R.color.white);
                break;
        }
        return true;
    }

    interface LongClickListener{
        void onLongClick(OnLongClickListener mOnLongClickListener);
    }
}
